package com.benromberg.jameshook;

import java.lang.instrument.Instrumentation;
import java.lang.instrument.UnmodifiableClassException;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

import com.benromberg.jameshook.internal.Transformer;

public class JamesHook {
	private static Logger logger = Logger.getLogger(JamesHook.class);
	private static Map<String, ClassHook<?>> hooks = new HashMap<String, ClassHook<?>>();

	private static Instrumentation instrumentation;

	public static void setInstrumentation(Instrumentation instrumentation) {
		JamesHook.instrumentation = instrumentation;
	}

	public static void registerHook(ClassHook<?> hook) {
		String className = hook.getGenericClass().getName();
		logger.info("registering hook for class " + className);
		hooks.put(className, hook);
		if (Transformer.getLoadedClasses().contains(className)) {
			logger.info("class already loaded: " + className + " - trying to reinstrument");
			if (instrumentation == null) {
				throw new RuntimeException("instrumentation not initialized!");
			}
			try {
				instrumentation.retransformClasses(hook.getGenericClass());
			} catch (UnmodifiableClassException e) {
				throw new RuntimeException("cannot retransform class " + className, e);
			}
		}
	}

	public static Map<String, ClassHook<?>> getHooks() {
		return hooks;
	}
}
